package com.zj.study.controller;

import com.zj.study.entity.User;
import com.zj.study.repository.PersonRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author ZhaoJiu
 * @since: 2021/7/22
 * @desc: r2dbc 操作mysql CRUD
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController {


  PersonRepository repository;

  public UserController(PersonRepository repository) {
    this.repository = repository;
  }

  /**
   * 修改用户
   *
   * @param user 用户
   * @return 操作结果
   */
  @PutMapping("/update")
  public Mono<ResponseEntity<String>> update(@RequestBody User user) {
    return repository.findById(user.getId())
        .flatMap(u -> repository.save(user)
            .then(Mono.just(new ResponseEntity<>("修改成功", HttpStatus.OK)))
            .doOnError(e -> log.error("添加用户异常，错误信息为【{}】", e.getMessage())))
        .defaultIfEmpty(new ResponseEntity<>("用户未找到", HttpStatus.NOT_FOUND));
  }

  /**
   * 根据id查询
   *
   * @param id 用户id
   * @return Mono
   */
  @GetMapping("{id}")
  public Mono<User> findById(@PathVariable String id) {

    return repository.findById(id);
  }

  /**
   * 添加用户
   *
   * @param user 用户信息
   * @return 操作结果
   */
  @PostMapping("save")
  public Mono<User> save(@RequestBody User user) {
    return repository.save(user);
  }

  /**
   * 查询所有
   *
   * @return 操作结果
   */
  @GetMapping("/list")
  public Flux<User> findAll() {
    return repository.findAll();
  }

  /**
   * 删除
   *
   * @param id 用户id
   * @return 操作结果
   */
  @DeleteMapping("{id}")
  public Mono<ResponseEntity<String>> delete(@PathVariable String id) {

    return repository.findById(id)
        .flatMap(u -> repository.deleteById(id)
            .then(Mono.just(new ResponseEntity<>("删除成功", HttpStatus.OK)))
            .doOnError(e -> log.error("删除用户异常，错误信息为【{}】", e.getMessage())))
        .defaultIfEmpty(new ResponseEntity<>("没有该用户", HttpStatus.NOT_FOUND));

  }

}
